package cn.ldf.keepaccounts.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.ldf.keepaccounts.dao.GameRecordsDao;
import cn.ldf.keepaccounts.entity.event.GameRecordsEvent;
import cn.ldf.keepaccounts.entity.pojo.GameRecords;
import cn.ldf.keepaccounts.entity.pojo.Members;
import cn.ldf.keepaccounts.enums.WsOptionEnum;
import cn.ldf.keepaccounts.service.GameRecordsService;
import cn.ldf.keepaccounts.service.MembersService;
import cn.ldf.keepaccounts.service.RoomsService;
import cn.ldf.keepaccounts.utils.ExceptionUtil;
import cn.ldf.keepaccounts.websocket.RoomsWebsocket;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 支付记录表(GameRecords)表服务实现类
 *
 * @author 清峰
 * @since 2025-02-17 09:37:44
 */
@Service("gameRecordsService")
public class GameRecordsServiceImpl extends ServiceImpl<GameRecordsDao, GameRecords> implements GameRecordsService {

    @Resource
    private RoomsService roomsService;
    @Resource
    private MembersService membersService;

    @Override
    public List<GameRecords> getListByRoomId(String roomId) {
        return this.lambdaQuery().eq(GameRecords::getRoomId, roomId).list();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public GameRecords addGameRecords(GameRecords gameRecords) {
        //自己不能向自己支付
        ExceptionUtil.throwMsg(() -> gameRecords.getPayerOpenId().equals(gameRecords.getPayeeOpenId()), "不能向自己支付");
        if (this.save(gameRecords)) {
            String roomId = gameRecords.getRoomId();
            ExceptionUtil.throwMsg(() -> roomsService.isDissolutionRooms(roomId), "该房间已结算,无法进行支付交易");
            List<Members> membersList = membersService.getNoSettledByRoomId(roomId);
            ExceptionUtil.throwMsg(() -> CollUtil.isEmpty(membersList), "未查询到该房间成员信息");
            //支付方房间成员积分流转
            membersList.stream().filter(members -> members.getOpenId().equals(gameRecords.getPayerOpenId())).forEach(members -> { members.setScore(members.getScore() - gameRecords.getAmount());
                membersService.updateById(members);});
            //收款方房间成员积分流转
            membersList.stream().filter(members -> members.getOpenId().equals(gameRecords.getPayeeOpenId())).forEach(members -> { members.setScore(members.getScore() + gameRecords.getAmount());
                membersService.updateById(members);});
            //发送ws消息给房间内所有用户
            GameRecordsEvent gameRecordsEvent = GameRecordsEvent.builder().wsOptionEnum(WsOptionEnum.ADD_GAME_RECORDS).gameRecords(gameRecords).membersList(membersList).build();
            RoomsWebsocket.sendInfo(gameRecordsEvent, gameRecords.getRoomId());
        }
        return gameRecords;
    }
}

